package com.code.family.filter;

import com.code.family.utils.JwtUtils;
import com.google.gson.Gson;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import com.code.family.utils.ResultVo;

import java.io.IOException;

/**
 * 登录检查过滤器
 * @author 上玄
 */
@Slf4j
@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.info("LoginCheckFilter");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求的URI
        String uri = request.getRequestURI();
        //判断请求的URI是否是登录页
        if (uri.contains("/login")) {
            filterChain.doFilter(servletRequest, servletResponse);
            // 放行
        } else {
            //获取JWT令牌
            String token = request.getHeader("token");
            if (token != null && !token.isEmpty()) {
                //验证JWT令牌
                try {
                    // 解析jwt
                    Claims content = JwtUtils.parseJwt(token);
                    log.info("JWT令牌验证成功，放行,{}", content);
                } catch (Exception e) {
                    log.info(e.getMessage());
                    //JWT令牌验证失败，并且返回json错误
                    log.info("JWT令牌验证失败");
                    Gson gson = new Gson();
                    response.setContentType("application/json;charset=utf-8");
                    response.getWriter().write(gson.toJson(ResultVo.error("NOT_LOGIN")));
                    return;
                }
                filterChain.doFilter(servletRequest, servletResponse);
                // 放行
                log.info("JWT令牌验证成功，放行");
            } else {
                //没有JWT令牌，并且返回json错误
                log.info("没有JWT令牌，并且返回json错误");
                Gson gson = new Gson();
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().write(gson.toJson(ResultVo.error("NOT_LOGIN")));
            }
        }
    }
}
